﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using OnlineVideos.Data;
using Common.Library;
using System.IO;
using System.ServiceModel.Syndication;
using System.Xml;
using System.Text;
using System.Collections.ObjectModel;
using TweetSharp;
using System.Threading;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Microsoft.CSharp;
using Microsoft.Phone.Shell;
using OnlineVideos.UI;
using OnlineVideos.Entities;
using System.Threading.Tasks;
using System.Collections;
using System.Globalization;
using Microsoft.Phone.Globalization;
using Windows.Storage;
using System.IO.IsolatedStorage;
using System.Windows.Media.Imaging;
using Common.Utilities;

namespace Social_Celebrities
{
    public class FacebookClass
    {
        public SyndicationItem item
        {
            get;
            set;
        }
        public string Commentcount
        {
            get;
            set;
        }
    }
    public class commentsclass
    {
        public string Name
        {
            get;
            set;
        }
        public string Comment
        {
            get;
            set;
        }
        public DateTime Date
        {
            get;
            set;
        }
    }
    public partial class MainPage : PhoneApplicationPage
    {
        List<CelebrityDetails> CelebrityDetailsList = new List<CelebrityDetails>();
        TwitterLoginPage p = new TwitterLoginPage();
        public ObservableCollection<FacebookClass> FeedList = new ObservableCollection<FacebookClass>();
        public ObservableCollection<SyndicationItem> BloggerList = new ObservableCollection<SyndicationItem>();
        public ObservableCollection<TwitterStatus> TwitterList = new ObservableCollection<TwitterStatus>();
        public IDictionary<string, ObservableCollection<commentsclass>> commentsDic = default(Dictionary<string, ObservableCollection<commentsclass>>);
        public MainPage()
        {
            InitializeComponent();
            Loaded += MainPage_Loaded;
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            LoadPersons();
            FeedList.Clear();
            TwitterList.Clear();
            BloggerList.Clear();
            feedListBox.ItemsSource = FeedList;
            tweetList.ItemsSource = TwitterList;
            BlogList.ItemsSource = BloggerList;
            LoadFeeds();
            //LoadAds();
        }
        private void LoadPersons()
        {
            try
            {
                List<CelebrityDetails> celeb = new List<CelebrityDetails>();
                CelebrityDetailsList = Task.Run(async () => await Constants.connection.Table<CastProfile>().ToListAsync()).Result.Distinct().Select(i => new CelebrityDetails() { PersonID = i.PersonID, PersonName = i.Name.ToLower(), Image = i.FlickrPersonImageUrl, Alphabet = i.Name.ToLower().Trim().Substring(0, 1) }).ToList();
                foreach (var ss in CelebrityDetailsList)
                {
                    CelebrityDetails cb = new CelebrityDetails();
                    cb.PersonID = ss.PersonID;
                    cb.PersonName = ss.PersonName;
                    cb.Alphabet = ss.Alphabet;
                    cb.Image = ss.Image;
                    Constants.UIThread = true;
                    if(!string.IsNullOrEmpty(ss.Image))
                    cb.PersonImage = new BitmapImage(new Uri(ss.Image,UriKind.Absolute));
                    else
                        cb.PersonImage = ResourceHelper.getpersonTileImage(ss.PersonID.ToString() + ".jpg");                   
                    Constants.UIThread = false;
                    celeb.Add(cb);
                }
                List<AlphaKeyGroup<CelebrityDetails>> DataSource = AlphaKeyGroup<CelebrityDetails>.CreateGroups(celeb, System.Threading.Thread.CurrentThread.CurrentUICulture, (CelebrityDetails s) => { return s.PersonName; }, true);
                listCelebrities.ItemsSource = DataSource;
                AppSettings.BackgroundAgenError = "LoadPersons Method in MainPage.xaml.cs is Successfull...!!!";
            }
            catch (Exception ex)
            {
                //Exceptions.SendErrortoMail("Exception at LoadPersons Method in Main Page.xaml.cs Page and the error is " + " " + ex.Message + " " + ex.StackTrace);
                Exceptions.SaveOrSendExceptions("Exception at LoadPersons Method in MainPage.xaml.cs", ex);
                AppSettings.BackgroundAgenError = ex.Message;
            }
        }

        private void LoadFeeds()
        {
            try
            {
                commentsDic = new Dictionary<string, ObservableCollection<commentsclass>>();
                List<Phone_SocialFeed> feed = Task.Run(async () => await Constants.connection.Table<Phone_SocialFeed>().Where(i => i.FeedType == "Facebook" || i.FeedType == "FaceBook").ToListAsync()).Result;
                foreach (Phone_SocialFeed ps in feed)
                {
                    if (!string.IsNullOrEmpty(ps.FeedLink))
                    {
                        LoadFromOnline(ps.FeedLink);
                    }
                }
                List<Phone_SocialFeed> feed1 = Task.Run(async () => await Constants.connection.Table<Phone_SocialFeed>().Where(i => i.FeedType == "Twitter" || i.FeedType == "twitter").ToListAsync()).Result;
                foreach (Phone_SocialFeed ps in feed1)
                {
                    if (!string.IsNullOrEmpty(ps.FeedLink))
                    {
                        if (ps.FeedLink.Contains("="))
                            LoadFromTwitter(ps.FeedLink.Substring(ps.FeedLink.IndexOf("=") + 1));
                        else
                            LoadFromTwitter(ps.FeedLink);
                    }
                }
                List<Phone_SocialFeed> feed2 = Task.Run(async () => await Constants.connection.Table<Phone_SocialFeed>().Where(i => i.FeedType == "blog" || i.FeedType == "Blog").ToListAsync()).Result;
                foreach (Phone_SocialFeed ps in feed2)
                {
                    if (!string.IsNullOrEmpty(ps.FeedLink))
                    {
                        if (ps.FeedLink.Contains("blogspot.com/") || ps.FeedLink.Contains("blogspot.in/"))
                            LoadFromBlogger(ps.FeedLink + "feeds/posts/default?alt=rss");
                        else if (ps.FeedLink.Contains("wordpress.com/") || ps.FeedLink.Contains("wordpress.in/"))
                            LoadFromBlogger(ps.FeedLink + "feed");
                        else if (ps.FeedLink.Contains("tumblr.com/") || ps.FeedLink.Contains("tumblr.in/"))
                            LoadFromBlogger(ps.FeedLink + "rss");
                    }
                }
                AppSettings.BackgroundAgenError = "LoadFeeds Method in MainPage.xaml.cs is Successfull..!!!";
            }
            catch (Exception ex)
            {
               // Exceptions.SendErrortoMail("Exception at LoadFeeds Method in Main Page.xaml.cs Page and the error is " + " " + ex.Message + " " + ex.StackTrace);
                Exceptions.SaveOrSendExceptions("Exception at LoadFeeds Method in MainPage.xaml.cs", ex);
                AppSettings.BackgroundAgenError = ex.Message;
            }
        }

        private void LoadFromBlogger(string CelebrityLink)
        {
            WebClient webClient = new WebClient();
            webClient.OpenReadCompleted += webClient_OpenReadCompleted;
            webClient.OpenReadAsync(new System.Uri(CelebrityLink), "Blog");
        }

        private void LoadFromTwitter(string CelebrityLink)
        {
            try
            {
                var service = new TwitterService("LYTy3T8P556GxqRymimhwA", "5TSKipEjESOAcdBsViWm2E1RVxFEN1Ooh0nRwIj7RsY");
                if (p.getAccessToken() != null)
                {
                    string[] Tokens = new string[2];
                    Tokens = p.ReturnTokens(p.getAccessToken());
                    if (Tokens[0] != null)
                    {
                        service.AuthenticateWith(Tokens[0], Tokens[1]);
                        service.ListTweetsOnUserTimeline(new ListTweetsOnUserTimelineOptions() { ScreenName = CelebrityLink }, (ts, rep) =>
                        {
                            if (rep.StatusCode == HttpStatusCode.OK)
                            {
                                Deployment.Current.Dispatcher.BeginInvoke((Action)(() =>
                                {
                                    foreach (TwitterStatus si in ts.Take(2))
                                    {
                                        TwitterList.Add(si);
                                    }
                                }));
                            }
                        });
                    }
                }
                AppSettings.BackgroundAgenError = "LoadFromTwitter Method in MainPage.xaml.cs is Successfull..!!";
            }
            catch (Exception ex)
            {
                //Exceptions.SendErrortoMail("Exception at LoadFromTwitter Method in Main Page.xaml.cs Page and the error is " + " " + ex.Message + " " + ex.StackTrace);
                Exceptions.SaveOrSendExceptions("Exception at LoadFromTwitter Method in MainPage.xaml.cs", ex);
                AppSettings.BackgroundAgenError = ex.Message;
            }
        }

        private void LoadFromOnline(string CelebrityLink)
        {
            WebClient webClient = new WebClient();
            webClient.OpenReadCompleted += webClient_OpenReadCompleted;
            webClient.OpenReadAsync(new System.Uri(CelebrityLink), "FB");
        }

        void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            try
            {
                if (e.Error != null)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show(e.Error.Message);
                    });
                }
                else
                {
                    Stream str = e.Result;
                    str.Position = 0;
                    string ReturnValue = string.Empty;
                    using (var reader = new StreamReader(str, Encoding.UTF8))
                    {
                        ReturnValue = reader.ReadToEnd();
                    }
                    ReturnValue = ReturnValue.Replace("+00:00", "").Replace(" <access:restriction relationship=\"deny\" xmlns:access=\"http://www.bloglines.com/about/specs/fac-1.0\" />", "");
                    UpdateFeedList(ReturnValue, e.UserState.ToString());
                    str.Close();
                }
                AppSettings.BackgroundAgenError = "LoadFromOnline Method in MainPage.xaml.cs Completed Successfull..!!";
            }
            catch (Exception ex)
            {
                //Exceptions.SendErrortoMail("Exception at LoadFromOnline Method in Main Page.xaml.cs Page and the error is " + " " + ex.Message + " " + ex.StackTrace);
                Exceptions.SaveOrSendExceptions("Exception at LoadFromOnline Method in Main Page.xaml.cs file", ex);
                AppSettings.BackgroundAgenError = ex.Message;
            }
        }

        private void UpdateFeedList(string feedXML, string FeedType)
        {
            try
            {
                StringReader stringReader = new StringReader(feedXML);
                XmlReader xmlReader = XmlReader.Create(stringReader);
                SyndicationFeed feed = SyndicationFeed.Load(xmlReader);
                if (null == feed) return;
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    foreach (SyndicationItem si in feed.Items.Take(2))
                    {
                        if (FeedType == "FB")
                        {
                            string PostId = string.Empty;
                            if (!string.IsNullOrEmpty(AppSettings.FaceBookAccessToken))
                            {
                                Facebook.FacebookClient face = new Facebook.FacebookClient(AppSettings.FaceBookAccessToken);
                                string Link = si.Links.FirstOrDefault().Uri.ToString();
                                if (Link.Contains("fbid="))
                                {
                                    PostId = Link.Substring(Link.IndexOf('=') + 1, ((Link.IndexOf('&') - 1) - Link.IndexOf('=')));
                                }
                                else if (Link.Contains("?type=1") || Link.Contains("&type=1"))
                                {
                                    string lin = Link.Replace("/?type=1", "").Replace("?set=","").Replace("&type=1","");
                                    PostId = lin.Substring(lin.LastIndexOf('/') + 1);
                                }
                                //else if (Link.Contains("&type=1"))
                                //{
                                //    string linkid = Link.Replace("&type=1", "");
                                //    PostId = linkid.Substring(linkid.LastIndexOf('.')+1);
                                    
                                //}
                                else if (Link.Contains("video.php?v="))
                                {
                                    PostId = Link.Substring(Link.LastIndexOf("?v=") + 3);
                                }
                                else
                                {
                                    PostId = Link.Substring(Link.LastIndexOf('/') + 1);
                                }
                                face.GetAsync("/" + PostId + "/comments", new Dictionary<string, object> { { "fields", "id,message,from,created_time" } }, si);
                                face.GetCompleted += face_GetCompleted;
                            }
                            else
                            {
                                ObservableCollection<commentsclass> commentsList = new ObservableCollection<commentsclass>();
                                FacebookClass fc = new FacebookClass();
                                fc.item = si;
                                if (commentsList.Count > 99)
                                    fc.Commentcount = commentsList.Count.ToString() + "+";
                                else
                                    fc.Commentcount = commentsList.Count.ToString();
                                Deployment.Current.Dispatcher.BeginInvoke(() =>
                                {
                                    FeedList.Add(fc);
                                });
                                commentsDic.Add(si.Id, commentsList);
                            }
                        }
                        else
                            BloggerList.Add(si);
                    }
                });
                AppSettings.BackgroundAgenError = "UpdateFeedList Method in MainPage.xaml.cs Completed Succesfully..!!";
            }
            catch (Exception ex)
            {
                //Exceptions.SendErrortoMail("Exception at UpdateFeedList Method in Main Page.xaml.cs Page and the error is " + " " + ex.Message + " " + ex.StackTrace);
                Exceptions.SaveOrSendExceptions("Exception at UpdateFeedList Method in Main Page.xaml.cs Page", ex);
                AppSettings.BackgroundAgenError = ex.Message;
            }
        }

        void face_GetCompleted(object sender, Facebook.FacebookApiEventArgs e)
        {
            try
            {
                if (e.Error == null)
                {
                    ObservableCollection<commentsclass> commentsList = new ObservableCollection<commentsclass>();
                    JObject o1 = JObject.Parse(e.GetResultData().ToString());
                    JArray a = (JArray)o1["data"];
                    foreach (var o in a)
                    {
                        commentsclass cc = new commentsclass();
                        cc.Name = (string)o["from"]["name"];
                        cc.Comment = (string)o["message"];
                        try
                        {
                            string date = (string)o["created_time"];
                            date = date.Split(' ')[0].ToString();
                            //string ab = date.ToString(@"yyyy/MM/dd HH:mm:ss");
                            //DateTime dt = Convert.ToDateTime(date);
                            DateTime dt = DateTime.Parse(date);
                            cc.Date = dt;
                        }
                       catch(Exception ex)
                        {
                            string b = ex.Message;      
                        }
                        commentsList.Add(cc);
                    }
                    FacebookClass fc = new FacebookClass();
                    fc.item = ((SyndicationItem)e.UserState);
                    if (commentsList.Count > 99)
                        fc.Commentcount = commentsList.Count.ToString() + "+";
                    else
                        fc.Commentcount = commentsList.Count.ToString();
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        FeedList.Add(fc);
                    });
                    commentsDic.Add(((SyndicationItem)e.UserState).Id, commentsList);
                    AppSettings.BackgroundAgenError = "face_GetCompleted Method in MainPage.xaml.cs Completed Successfully..!!!";
                }
            }
            catch (Exception ex)
            {
                // Exceptions.SendErrortoMail("Exception at face_GetCompleted Method in Main Page.xaml.cs Page and the error is " + " " + ex.Message + " " + ex.StackTrace);
                Exceptions.SaveOrSendExceptions("Exception at face_GetCompleted Method in MainPage.xaml.cs page", ex);
                AppSettings.BackgroundAgenError = ex.Message;
            }
        }

        private void StackPanel_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            StackPanel stk = sender as StackPanel;
            AppSettings.PersonID = stk.Tag.ToString();
            NavigationService.Navigate(new Uri("/Feeds.xaml?PersonId=" + stk.Tag, UriKind.Relative));
        }

        private void imgTitle_MouseEnter(object sender, MouseButtonEventArgs e)
        {
            NavigationService.Navigate(NavigationHelper.MainPanoramaPage);
        }

        private void ApplicationBarIconButton_Click_1(object sender, EventArgs e)
        {
            if ((sender as ApplicationBarIconButton).Text == "Accounts")
            {
                NavigationService.Navigate(new Uri("/Views/AddAccount.xaml", UriKind.Relative));
            }
            else
            {
                NavigationService.Navigate(new Uri("/Views/onlineshare.xaml", UriKind.Relative));
            }
        }

        private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (string.IsNullOrEmpty(AppSettings.FaceBookAccessToken))
            {
                NavigationService.Navigate(new Uri("/Views/FacebookLoginPage.xaml", UriKind.Relative));
            }
        }

        private void feedListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (feedListBox.SelectedIndex == -1)
                return;
            if (string.IsNullOrEmpty(AppSettings.FaceBookAccessToken))
            {
                NavigationService.Navigate(new Uri("/Views/FacebookLoginPage.xaml", UriKind.Relative));
                feedListBox.SelectedIndex = -1;
            }
            else
            {
                Constants.SelectedSyndicationItem[0] = (SyndicationItem)((FacebookClass)feedListBox.SelectedItem).item;
                Constants.SelectedSyndicationItem[1] = commentsDic.Where(i => i.Key == ((SyndicationItem)((FacebookClass)feedListBox.SelectedItem).item).Id).FirstOrDefault().Value;
                NavigationService.Navigate(new Uri("/Views/feedPage.xaml?FeedType=FaceBook", UriKind.Relative));
                feedListBox.SelectedIndex = -1;
            }
        }

        private void tweetList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (tweetList.SelectedIndex == -1)
                return;
            if (p.getAccessToken() == null)
            {
                NavigationService.Navigate(new Uri("/Views/TwitterLoginPage.xaml", UriKind.Relative));
                tweetList.SelectedIndex = -1;
            }
            else
            {
                Constants.SelectedSyndicationItem[0] = (TwitterStatus)tweetList.SelectedItem;
                NavigationService.Navigate(new Uri("/Views/feedPage.xaml?FeedType=Twitter", UriKind.Relative));
                tweetList.SelectedIndex = -1;
            }
        }

        private void Image_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
        {
            if (p.getAccessToken() == null)
            {
                NavigationService.Navigate(new Uri("/Views/TwitterLoginPage.xaml", UriKind.Relative));
            }
        }

        private void BlogList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (string.IsNullOrEmpty(AppSettings.BloggerAccessToken))
            {
                NavigationService.Navigate(new Uri("/Views/BloggerLogin.xaml", UriKind.Relative));
                BlogList.SelectedIndex = -1;
            }
            else
            {
                if (BlogList.SelectedIndex == -1)
                    return;
                Constants.SelectedSyndicationItem[0] = (SyndicationItem)BlogList.SelectedItem;
                NavigationService.Navigate(new Uri("/Views/feedPage.xaml?FeedType=Blog", UriKind.Relative));
                BlogList.SelectedIndex = -1;
            }
        }

        private void BlogComment_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (string.IsNullOrEmpty(AppSettings.BloggerAccessToken))
            {
                NavigationService.Navigate(new Uri("/Views/BloggerLogin.xaml", UriKind.Relative));
            }
        }

        private void Image_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {
            ListBox list = (ListBox)GetParentDependencyObjectFromVisualTree((sender as Image), typeof(ListBox));
            list.Visibility = Visibility.Collapsed;
        }
        public static DependencyObject GetParentDependencyObjectFromVisualTree(DependencyObject startObject, Type type)
        {
            DependencyObject parent = startObject;
            while (parent != null)
            {
                if (type.IsInstanceOfType(parent))
                    break;
                else
                    parent = VisualTreeHelper.GetParent(parent);
            }
            return parent;
        }

        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/AddCast.xaml", UriKind.Relative));
        }
       
        private void pvtMainDetails_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if ((((sender as Pivot).SelectedItem as PivotItem).Header as TextBlock).Text == "celebrities")
                {
                    this.ApplicationBar.IsVisible = true;
                    if (LayoutRoot.RowDefinitions.Count > 1)
                    {
                        RowDefinition myrow = LayoutRoot.RowDefinitions[1];
                        LayoutRoot.Children.RemoveAt(1);
                        LayoutRoot.RowDefinitions.Remove(myrow);
                    }
                    ApplicationBarIconButton b = (ApplicationBarIconButton)ApplicationBar.Buttons[0];
                    b.Text = "Download";
                    b.IconUri = new Uri("/Images/appbar.download.rest.png", UriKind.RelativeOrAbsolute);

                    
                    if (this.ApplicationBar.Buttons.Count < 4)
                    {
                        ApplicationBarIconButton appBaricon = null;
                        appBaricon = new ApplicationBarIconButton(new Uri("/Images/question.png", UriKind.RelativeOrAbsolute));
                        appBaricon.Text = "get started";
                        appBaricon.Click += GetStarted_Click_1;
                        this.ApplicationBar.Buttons.Add(appBaricon);
                    }
                    if (this.ApplicationBar.Buttons.Count == 4)
                    {
                        ApplicationBarIconButton b1 = (ApplicationBarIconButton)ApplicationBar.Buttons[2];
                        this.ApplicationBar.Buttons.Remove(b1);
                        ApplicationBarIconButton b2 = (ApplicationBarIconButton)ApplicationBar.Buttons[2];
                        b2.Text = "get started";
                        b2.IconUri = new Uri("/Images/question.png", UriKind.RelativeOrAbsolute);
                        b2.Click += GetStarted_Click_1;
                    }
                }
                else if ((((sender as Pivot).SelectedItem as PivotItem).Header as TextBlock).Text == "about")
                {

                    this.ApplicationBar.IsVisible = false;
                    if (LayoutRoot.RowDefinitions.Count > 1)
                    {
                        RowDefinition myrow = LayoutRoot.RowDefinitions[1];
                        LayoutRoot.Children.RemoveAt(1);
                        LayoutRoot.RowDefinitions.Remove(myrow);
                    }
                }
                else if ((((sender as Pivot).SelectedItem as PivotItem).Header as TextBlock).Text == "news")
                {
                    this.ApplicationBar.IsVisible = true;
                    RowDefinition myrow = new RowDefinition();
                    myrow.Height = new GridLength(80, GridUnitType.Pixel);
                    LayoutRoot.RowDefinitions.Add(myrow);
                    StackPanel adcaststk = new StackPanel();
                    adcaststk.Name = "adcaststk";
                    adcaststk.Height = 80;
                    adcaststk.SetValue(Grid.RowProperty, 1);
                    LayoutRoot.Children.Add(adcaststk);
                    PageHelper.LoadAdControl(LayoutRoot, adcaststk, 1);
                    ApplicationBarIconButton b1 = (ApplicationBarIconButton)ApplicationBar.Buttons[2];
                    this.ApplicationBar.Buttons.Remove(b1);
                    ApplicationBarIconButton b = (ApplicationBarIconButton)ApplicationBar.Buttons[0];
                    b.Text = "Accounts";
                    b.IconUri = new Uri("/Images/feature.settings.png", UriKind.RelativeOrAbsolute);
                    if (this.ApplicationBar.Buttons.Count < 2)
                    {
                        ApplicationBarIconButton appBaricon = null;
                        appBaricon = new ApplicationBarIconButton(new Uri("/Images/appbar.add.rest.png", UriKind.RelativeOrAbsolute));
                        appBaricon.Text = "Add Person";
                        appBaricon.Click += ApplicationBarIconButton_Click;
                        this.ApplicationBar.Buttons.Add(appBaricon);
                    }
                    if (this.ApplicationBar.Buttons.Count < 3)
                    {
                        ApplicationBarIconButton appBaricon1 = null;
                        appBaricon1 = new ApplicationBarIconButton(new Uri("/Images/refresh.png", UriKind.RelativeOrAbsolute));
                        appBaricon1.Text = "Refresh";
                        appBaricon1.Click += appBaricon1_Click;
                        this.ApplicationBar.Buttons.Add(appBaricon1);
                    }
                    //ApplicationBarIconButton reldbtn = (ApplicationBarIconButton)ApplicationBar.Buttons[0];
                    //b.Text = "Reload";
                    //reldbtn.IconUri = new Uri("/Images/refresh.png", UriKind.RelativeOrAbsolute);
                }
                AppSettings.BackgroundAgenError = "pvtMainDetails_SelectionChanged Event in Main Page.xaml.cs Completed Successfully..!!";
            }
            catch (Exception ex)
            {
                //Exceptions.SendErrortoMail("Exception at pvtMainDetails_SelectionChanged Method in Main Page.xaml.cs Page and the error is " + " " + ex.Message + " " + ex.StackTrace);
                Exceptions.SaveOrSendExceptions("Exception at pvtMainDetails_SelectionChanged Event in MainPage.xaml.cs page..", ex);
                AppSettings.BackgroundAgenError = ex.Message;
            }
        }
       
        void appBaricon1_Click(object sender, EventArgs e)
        {           
            LoadFeeds();
        }

        private void deletecelebrity_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                int deletePersonid = Convert.ToInt32((sender as MenuItem).Tag.ToString());
                CastProfile cp = Task.Run(async () => await Constants.connection.Table<CastProfile>().Where(i => i.PersonID == deletePersonid).FirstOrDefaultAsync()).Result;
                Constants.connection.DeleteAsync(cp);
                List<Phone_SocialFeed> lps = Task.Run(async () => await Constants.connection.Table<Phone_SocialFeed>().Where(i => i.PersonId == deletePersonid).ToListAsync()).Result;
                foreach (Phone_SocialFeed feed in lps)
                {
                    Constants.connection.DeleteAsync(feed);
                }
                if (Task.Run(async () => await Storage.FileExists("/" + ResourceHelper.ProjectName + "/Images/PersonImages/" + deletePersonid + ".jpg")).Result)
                {
                    string imagefile = "/" + ResourceHelper.ProjectName + "/Images/PersonImages/" + deletePersonid + ".jpg";
                    string[] FoldersNames = imagefile.TrimStart('/').Split('/');
                    StorageFolder GetFolder = ApplicationData.Current.LocalFolder;
                    foreach (string foldername in FoldersNames)
                    {
                        if (foldername != FoldersNames[FoldersNames.Length - 1].ToString())
                            GetFolder = Task.Run(async () => await GetFolder.GetFolderAsync(foldername)).Result;
                    }

                    StorageFile GetFile = Task.Run(async () => await GetFolder.GetFileAsync(FoldersNames[FoldersNames.Length - 1].ToString())).Result;
                    Task.Run(async () => await GetFile.DeleteAsync());
                }
                LoadPersons();
                AppSettings.BackgroundAgenError = "deletecelebrity_Click event in MainPage.xaml.cs Completed Successfully..!!!!";
            }
            catch (Exception ex)
            {
                //Exceptions.SendErrortoMail("Exception at deletecelebrity_Click Method in Main Page.xaml.cs Page and the error is " + " " + ex.Message + " " + ex.StackTrace);
                Exceptions.SaveOrSendExceptions("Exception at deletecelebrity_Click Event in MainPage.xaml.cs page", ex);
                AppSettings.BackgroundAgenError = ex.Message;
            }
        }

        //private void ApplicationBarIconButton_Click_2(object sender, EventArgs e)
        //{
        //    NavigationService.Navigate(new Uri("/Views/BackAgentError.xaml", UriKind.Relative));
        //}

        private void Image_ImageOpened_1(object sender, RoutedEventArgs e)
        {
            var ss = (sender as Image);
        }

        private void editcelebrity_Click(object sender, RoutedEventArgs e)
        {
            Constants.editcelebrity = true;
            int Personid = Convert.ToInt32((sender as MenuItem).Tag.ToString());
            Constants.personid = Personid;
            NavigationService.Navigate(new Uri("/Views/AddCast.xaml", UriKind.Relative));
        }

        //private void ApplicationBarIconButton_Click_3(object sender, EventArgs e)
        //{
        //    NavigationService.Navigate(new Uri("/Views/Settings.xaml", UriKind.Relative));
        //}

        private void settings_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/Settings.xaml", UriKind.Relative));
        }       

        private void GetStarted_Click_1(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/HelpMenu.xaml", UriKind.Relative));
        }        
    }

    public class AlphaKeyGroup<T> : List<T>
    {
        public delegate string GetKeyDelegate(T item);
        public string Key { get; private set; }
        public AlphaKeyGroup(string key)
        {
            Key = key;
        }

        private static List<AlphaKeyGroup<T>> CreateGroups(SortedLocaleGrouping slg)
        {
            List<AlphaKeyGroup<T>> list = new List<AlphaKeyGroup<T>>();
            foreach (string key in slg.GroupDisplayNames)
            {
                list.Add(new AlphaKeyGroup<T>(key));
            }
            return list;
        }

        public static List<AlphaKeyGroup<T>> CreateGroups(IEnumerable<T> items, CultureInfo ci, GetKeyDelegate getKey, bool sort)
        {
            SortedLocaleGrouping slg = new SortedLocaleGrouping(ci);
            List<AlphaKeyGroup<T>> list = CreateGroups(slg);
            foreach (T item in items)
            {
                int index = 0;
                if (slg.SupportsPhonetics)
                {

                }
                else
                {
                    index = slg.GetGroupIndex(getKey(item));
                }
                if (index >= 0 && index < list.Count)
                {
                    list[index].Add(item);
                }
            }
            if (sort)
            {
                foreach (AlphaKeyGroup<T> group in list)
                {
                    group.Sort((c0, c1) => { return ci.CompareInfo.Compare(getKey(c0), getKey(c1)); });
                }
            }
            return list;
        }        
    }
}